<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="题库" prop="questionBankId">
        <question-bank-select v-model="queryParams.questionBankId" />
      </el-form-item>
      <el-form-item label="难度等级" prop="difficultyLevel">
        <el-input
          v-model="queryParams.difficultyLevel"
          placeholder="请输入难度等级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="题目分值" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入题目分值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否公开" prop="isPublic">
        <el-input
          v-model="queryParams.isPublic"
          placeholder="请输入是否公开"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用次数" prop="useCount">
        <el-input
          v-model="queryParams.useCount"
          placeholder="请输入使用次数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="正确次数" prop="correctCount">
        <el-input
          v-model="queryParams.correctCount"
          placeholder="请输入正确次数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:question:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['exam:question:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['exam:question:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['exam:question:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['exam:question:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="题目ID" align="center" prop="questionId" />
      <el-table-column label="题目标题" align="center" prop="questionTitle" width="200" />
      <el-table-column label="题目内容" align="center" prop="questionContent" width="300" />
      <el-table-column label="题目解析" align="center" prop="questionAnalysis" />
      <el-table-column label="难度等级" align="center" prop="difficultyLevel" />
      <el-table-column label="题目分值" align="center" prop="score" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="是否公开" align="center" prop="isPublic" />
      <el-table-column label="使用次数" align="center" prop="useCount" />
      <el-table-column label="正确次数" align="center" prop="correctCount" />
      <el-table-column label="标签" align="center" prop="tags" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['exam:question:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['exam:question:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['exam:question:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属题库" prop="questionBankIds">
          <question-bank-select v-model="form.questionBankIds" :multiple="true" />
        </el-form-item>
        <el-form-item label="题目标题" prop="questionTitle">
          <el-input v-model="form.questionTitle" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="题目内容" prop="questionContent">
          <editor v-model="form.questionContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="题目解析" prop="questionAnalysis">
          <el-input v-model="form.questionAnalysis" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="难度等级" prop="difficultyLevel">
          <el-input v-model="form.difficultyLevel" placeholder="请输入难度等级" />
        </el-form-item>
        <el-form-item label="题目分值" prop="score">
          <el-input v-model="form.score" placeholder="请输入题目分值" />
        </el-form-item>
        <el-form-item label="是否公开" prop="isPublic">
          <el-input v-model="form.isPublic" placeholder="请输入是否公开" />
        </el-form-item>
        <el-form-item label="使用次数" prop="useCount">
          <el-input v-model="form.useCount" placeholder="请输入使用次数" disabled />
        </el-form-item>
        <el-form-item label="正确次数" prop="correctCount">
          <el-input v-model="form.correctCount" placeholder="请输入正确次数" disabled />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :auto-upload="false"
        drag
        :on-change="handleFileChange"
        :file-list="upload.fileList">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的题目数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看题目详情对话框 -->
    <el-dialog title="题目详情" :visible.sync="viewOpen" width="70%" append-to-body>
      <div v-if="questionDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="题目ID">{{ questionDetail.questionId }}</el-descriptions-item>
          <el-descriptions-item label="题目分值">{{ questionDetail.score }}</el-descriptions-item>
          <el-descriptions-item label="题目类型">
            <el-tag v-if="questionDetail.questionType === '1'" type="primary">单选题</el-tag>
            <el-tag v-else-if="questionDetail.questionType === '2'" type="success">多选题</el-tag>
            <el-tag v-else-if="questionDetail.questionType === '3'" type="warning">判断题</el-tag>
            <el-tag v-else-if="questionDetail.questionType === '4'" type="info">填空题</el-tag>
            <el-tag v-else type="default">未知类型</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="难度等级">
            <el-tag v-if="questionDetail.difficultyLevel === '1'" type="success">简单</el-tag>
            <el-tag v-else-if="questionDetail.difficultyLevel === '2'" type="warning">中等</el-tag>
            <el-tag v-else-if="questionDetail.difficultyLevel === '3'" type="danger">困难</el-tag>
            <el-tag v-else type="info">{{ questionDetail.difficultyLevel }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="questionDetail.status === '0'" type="success">正常</el-tag>
            <el-tag v-else type="danger">停用</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="是否公开">
            <el-tag v-if="questionDetail.isPublic === '1'" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="使用次数">{{ questionDetail.useCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="正确次数">{{ questionDetail.correctCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="正确率">{{ questionDetail.useCount > 0 ? ((questionDetail.correctCount || 0) / questionDetail.useCount * 100).toFixed(2) + '%' : '0%' }}</el-descriptions-item>
          <el-descriptions-item label="分类ID">{{ questionDetail.categoryId || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ questionDetail.createBy }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ questionDetail.createTime }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="left">题目标题</el-divider>
        <div class="question-content">{{ questionDetail.questionTitle }}</div>
        
        <el-divider content-position="left">题目内容</el-divider>
        <div class="question-content" v-html="questionDetail.questionContent"></div>
        
        <!-- 选项显示 - 根据题目类型显示不同内容 -->
        <el-divider content-position="left">选项</el-divider>
        <div v-if="questionDetail.options && questionDetail.options.length > 0">
          <div v-for="(option, index) in questionDetail.options" :key="index" class="option-item">
            <el-tag :type="option.isCorrect ? 'success' : 'info'" size="small">
              {{ String.fromCharCode(65 + index) }}
            </el-tag>
            <span class="option-content">{{ option.optionContent }}</span>
          </div>
        </div>
        <div v-else class="no-data">
          <span v-if="questionDetail.questionType === '4'">填空题无选项</span>
          <span v-else>暂无选项信息</span>
        </div>

        <!-- 答案显示 - 新增答案字段显示 -->
        <el-divider content-position="left" v-if="questionDetail.answers && questionDetail.answers.length > 0">标准答案</el-divider>
        <div v-if="questionDetail.answers && questionDetail.answers.length > 0" class="answer-section">
          <div v-for="(answer, index) in questionDetail.answers" :key="index" class="answer-item">
            <el-tag type="success" size="small">答案{{ index + 1 }}</el-tag>
            <span class="answer-content">{{ answer.answerContent || answer.content }}</span>
          </div>
        </div>
        
        <el-divider content-position="left">题目解析</el-divider>
        <div class="question-content">{{ questionDetail.questionAnalysis || '暂无解析' }}</div>
        
        <el-divider content-position="left">标签</el-divider>
        <div class="question-content">{{ questionDetail.tags || '无标签' }}</div>
        
        <el-divider content-position="left">备注</el-divider>
        <div class="question-content">{{ questionDetail.remark || '无备注' }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion, importData, getQuestionDetailInfo } from "@/api/exam/question";
import QuestionBankSelect from "@/components/QuestionBankSelect";

export default {
  name: "Question",
  components: {
    QuestionBankSelect
  },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionBankId: null,
        questionTitle: null,
        questionContent: null,
        questionAnalysis: null,
        difficultyLevel: null,
        score: null,
        status: null,
        isPublic: null,
        useCount: null,
        correctCount: null,
        tags: null,
        remark: null
      },
      // 表单参数
      form: {
        questionId: null,
        questionBankIds: null,
        questionTitle: null,
        questionContent: null,
        questionAnalysis: null,
        difficultyLevel: null,
        score: null,
        status: "0",
        isPublic: null,
        useCount: null,
        correctCount: null,
        tags: null,
        remark: null
      },
      // 表单校验
      rules: {
        questionId: [
          { required: true, message: "题目ID不能为空", trigger: "blur" }
        ],
        questionTitle: [
          { required: true, message: "题目标题不能为空", trigger: "blur" }
        ],
        questionContent: [
          { required: true, message: "题目内容不能为空", trigger: "blur" }
        ],
        questionAnalysis: [
          { required: true, message: "题目解析不能为空", trigger: "blur" }
        ],
        difficultyLevel: [
          { required: true, message: "难度等级不能为空", trigger: "blur" }
        ],
        score: [
          { required: true, message: "题目分值不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        isPublic: [
          { required: true, message: "是否公开不能为空", trigger: "blur" }
        ]
      },
      // 导入参数
      upload: {
        title: "导入题目",
        open: false,
        headers: { Authorization: "Bearer " + this.$store.getters.token },
        fileList: [],
        updateSupport: false
      },
      // 查看题目详情对话框
      viewOpen: false,
      // 题目详情
      questionDetail: null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        questionId: null,
        questionBankIds: null,
        questionTitle: null,
        questionContent: null,
        questionAnalysis: null,
        difficultyLevel: null,
        score: null,
        status: "0",
        isPublic: null,
        useCount: null,
        correctCount: null,
        tags: null,
        tagIds:[],
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.questionId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const questionId = row.questionId || this.ids
      getQuestion(questionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改题目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.questionId != null) {
            updateQuestion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const questionIds = row.questionId || this.ids;
      this.$modal.confirm('是否确认删除题目编号为"' + questionIds + '"的数据项？').then(function() {
        return delQuestion(questionIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('exam/question/export', {
        ...this.queryParams
      }, `question_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入题目";
      this.upload.open = true;
      this.upload.fileList = [];
      this.upload.updateSupport = false;
    },
    /** 文件选择改变 */
    handleFileChange(file, fileList) {
      this.upload.fileList = fileList;
    },
    /** 提交上传文件 */
    submitFileForm() {
      if (this.upload.fileList.length === 0) {
        this.$modal.msgError("请选择要上传的文件");
        return;
      }
      
      const file = this.upload.fileList[0].raw;
      const loading = this.$loading({
        lock: true,
        text: '正在导入数据，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      importData(file, this.upload.updateSupport).then(response => {
        loading.close();
        this.upload.open = false;
        this.upload.fileList = [];
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      }).catch(() => {
        loading.close();
        this.upload.open = false;
        this.upload.fileList = [];
      });
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('exam/question/importTemplate', {}, `question_template_${new Date().getTime()}.xlsx`);
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewOpen = true;
      getQuestionDetailInfo(row.questionId).then(response => {
        this.questionDetail = response.data;
      });
    }
  }
};
</script>

<style scoped>
.question-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin: 10px 0;
  min-height: 40px;
  line-height: 1.6;
}

.option-item {
  display: flex;
  align-items: center;
  margin: 8px 0;
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.option-content {
  margin-left: 10px;
  flex: 1;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.answer-section {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.answer-item {
  display: flex;
  align-items: center;
  margin: 8px 0;
  padding: 8px;
  background-color: #e8f5e8;
  border-radius: 4px;
  border-left: 3px solid #67c23a;
}

.answer-content {
  margin-left: 10px;
  flex: 1;
  font-weight: 500;
}
</style>
